<?php
// подключение модуля поиска
//include_once INCLUDE_PATH . "/search.php";

// расширенный поиск
function pageSearchFull() {
	global $_Main, $_TPL;
	$tmpT = array ("site-title" => "autode.net - поиск автомобиля", "site-links" => "<h></h><t>Расширенные поиск</t>", "site-header" => "" );
	$_TPL->Load ( "page.search_full", "page-header" );
	$tmpT ["site-header"] = $_TPL->Show ( "page-header" );
	$_Main->MakePage ( "page.search_full", $tmpT, "page-search_full" );
	return 0;
}

// марки машин
function pageMark() {
	// имена файлов кэша
	$files = array (
		'models' => SEF::$arr[1].'_models',
		'mark'   => 'mark_'.SEF::$arr[1]
	);
	//
	$cache = array (
		
		'models'       => ''
	)
	if (Cache::Read($files['mark'])) {
		$cache['mark'] = Cache::Get($files['mark'], TRUE, 'mark');
	}
	// кэш блока моделей марки
	if (Cache::ReadHTML($cache['cache_models'])) {
		$cache['models'] = Cache::Get($cache['cache_models']);
		Cache::Clear($cache['cache_models']);
	} else {
		// поиск запрашиваемой марки в БД
		$mark = MySQL::Select('SELECT `mark_id`, `mark_ru`, `mark_eng` FROM `{p}marks` WHERE `mark_alias` = "'.SEF::$arr[1].'";');
		// 404-я вслучае ошибки 
		if (!$mark) {Core::page404(); return 0;}
		// формирование блока моделей
		TPL::Load('page.models');
		// сгруппированные модели
		$_SELECT = MySQL::Select('SELECT `model_eng`, `model_alias`, `model_group` FROM `{p}models` WHERE `mark_id` = '.$mark['mark_id'].' AND `model_code` < 0', MYSQL_SQUERY);
		$no_models = '';
		while (($model = MySQL::Fetch_array($_SELECT)) !== NULL) {
			TPL::makeBlock('models', 'model', array (
				'text' => $model['model_eng'],
				'href' => Conf::$site['site_url'].'/model/'.SEF::$arr[1].'/'.$model['model_alias']
			));
			$no_models .= ($no_models != '')?(','.$model['model_group']):($model['model_group']);
		}
		$sql = (isset($no_models))?(' AND `model_code` NOT IN ('.$no_models.')'):('');
		echo $sql;
		// оставшиеся модели
		$_SELECT = MySQL::Select('SELECT `model_eng`, `model_alias` FROM `{p}models` WHERE `mark_id` = '.$mark['mark_id'].' AND `model_code` >= 0'.$sql, MYSQL_SQUERY);
		while (($model = MySQL::Fetch_array($_SELECT)) !== NULL) {
			TPL::makeBlock('models', 'model', array (
				'text' => $model['model_eng'],
				'href' => Conf::$site['site_url'].'/model/'.SEF::$arr[1].'/'.$model['model_alias']
			));
		}
		// настройка параметров
		TPL::$vars['mark_name'] = $mark['mark_eng'].' модели';
		TPL::blockPage();
		// сохранение кода
		$p_set['models'] = TPL::$page['body'];
	}
	
	// кэш элементов страницы
	if (Cache::Read($cache_mark)) {
		// номер страницы
		$cache_page = 'page_'.(isset(SEF::$arr['page']))?(SEF::$arr['page']):(1);
		if (Cache::isSet($cache_mark, $cache_page)) {
			// считывание значений из кэша
			// title
			TPL::$page['title'] = Cache::Get($cache_name, 'title');
			// блоки
		}
	 
	
	
	// шаблон страницы
	TPL::Load('page.search');
	// title страницы
	TPL::$page['title'] = $p_set['title'] = 'Купить '.$mark['mark_eng'].' из Германии, продажа '.$mark['mark_ru'].' в Германии, стоимость, цены на autode.net';
	// search_title
	TPL::$vars['search_title'] = $p_set['search_title'] = 'Поиск автомобилей '.$mark['mark_eng'];
	// блок моделей
	TPL::setBlock('models', $p_set['models']);
	unset($p_set['models']);
	// поиск машин
	$_SELECT = MySQL::Select('EXPLAIN SELECT * FROM `tbl_markmodels` WHERE mark_id');
	$query = array (
		'count' => $_SELECT['rows'],
		'sql'   => ',`{p}markmodels` WHERE `mark_id` = '.$mark['mark_id']
	);
	// формирование таблицы
	//$count = makeTable($query);
	TPL::$vars['search_count'] = $count.' результата(ов) поиска'; 
	return 0;
}

// модели машин
function pageModel() {
	global $_MYSQL, $_SEF, $_Main, $_TPL;
	// ID марки
	$_SELECT = $_MYSQL->SELECT ( "SELECT `ma-id`, `display-name` FROM `{p}marks` WHERE `ma-name` = '" . $_GET [1] . "';" );
	if (! $_SELECT) {
		$_Main->Page404 ();
		return 0;
	}
	$mark_id = $_SELECT ["ma-id"];
	$mark_name = $_SELECT ["display-name"];
	// ID модели
	$_SELECT = $_MYSQL->SELECT ( "SELECT `mo-id`, `mo-code`, `mo-group`, `display-name` FROM `{p}models` WHERE `mark-id` = " . $mark_id . " AND `mo-name` = '" . $_GET [2] . "';" );
	if (! $_SELECT) {
		$_Main->Page404 ();
		return 0;
	}
	$model_id = $_SELECT ["mo-id"];
	$model_name = $_SELECT ["display-name"];
	$tmpT = array ("site-title" => "Купить " . $_GET [1] . " ", "site-links" => "<h>/search-full</h><t>Поиск легкового автомобиля</t><h>/mark/" . $_SEF->Encode ( $_GET [1] ) . "</h><t>" . $_GET [1] . "</t>", "title" => "Поиск автомобилей " . $_GET [1], "search-models" => "", "mark-name" => "Модели " . $_GET [1] . " " . $_GET [2], "model-links" => "", "search-rez" => "", "search-rows" => "", "search-pages" => "" );
	$bGroup = FALSE;
	$model_IDs = "";
	// сгруппированные модели                                                                 
	if ($_SELECT ["mo-code"] < 0) {
		// основные элементы
		$_TPL->Load ( "page.models", "page-models" );
		$_TPL->Load ( "page.models", "div-models" );
		// ссылки на модели
		$_MODELS = $_MYSQL->SELECT ( "SELECT `mo-id`, `mo-name`, `display-name` FROM `{p}models` WHERE `mark-id` = " . $mark_id . " AND `mo-code` IN (" . $_SELECT ["mo-group"] . ");", MYSQL_SQUERY );
		while ( $model = $_MYSQL->FETCH_Array ( $_MODELS ) ) {
			$tmpT ["model-links"] .= $_TPL->Show ( "div-models", array ("href" => "{site_url}/model/" . $_SEF->Encode ( $_GET [1] ) . "/" . $_SEF->Encode ( $model ["mo-name"] ), "text" => $model ["mo-name"] ), TPL_NOCLEAR );
			$model_IDs .= ((($model_IDs != "") ? (", ") : ("")) . $model ["mo-id"]);
		}
	} else {
		$model_IDs = $_SELECT ["mo-id"];
		if ($_SELECT ["mo-code"] != 0) {
			$_MODELS = $_MYSQL->SELECT ( "SELECT `mo-name`, `display-name` FROM `{p}models` WHERE `mark-id` = " . $mark_id . " AND `mo-group` LIKE '%" . $_SELECT ["mo-code"] . "%'" );
			if ($_MODELS) {
				$bGroup = TRUE;
				$model_N = $_MODELS ["mo-name"];
			}
		}
	}
	if ($bGroup) {
		$tmpT ["title"] .= " - " . $_MODELS ["mo-name"] . " - " . $_GET [2];
		$tmpT ["site-title"] .= $_MODELS ["mo-name"] . " " . $_GET [2] . "  из Германии, продажа " . $mark_name . " " . $_MODELS ["display-name"] . " " . $model_name . " в Германии, стоимость, цены на autode.net";
		$tmpT ["site-links"] .= "<h>/model/" . $_SEF->Encode ( $_GET [1] ) . "/" . $_SEF->Encode ( $_MODELS ["mo-name"] ) . "</h><t>" . $_MODELS ["mo-name"] . "</t><h></h><t>" . $_GET [2] . "</t>";
	} else {
		$tmpT ["title"] .= " - " . $_GET [2];
		$tmpT ["site-title"] .= $_GET [2] . "  из Германии, продажа " . $mark_name . " " . $model_name . " в Германии, стоимость, цены на autode.net";
		$tmpT ["site-links"] .= "<h></h><t>" . $_GET [2] . "</t>";
	}
	if ($_SELECT ["mo-code"] < 0) {
		$tmpT ["search-models"] = $_TPL->Show ( "page-models", $tmpT );
	}
	$_TPL->Clear ( "div-models" );
	// обновление запроса
	if ((date ( "i" ) > 10 && date ( "i" ) < 30) || (date ( "i" ) > 40 && date ( "i" ) <= 59)) {
		if ($_SESSION ["sUpdate"] == 1) {
			if (isset ( $_SESSION ["nPages"] ) && $_SESSION ["nPages"] !== 0) {
				$bCount = TRUE;
			} else {
				$bCount = FALSE;
			}
		} else {
			$bCount = FALSE;
		}
		$_SESSION ["sUpdate"] = 1;
	} else {
		$bCount = FALSE;
		$_SESSION ["sUpdate"] = 0;
	}
	// поиск машин
	if (! $bCount) {
		$_SELECT = $_MYSQL->SELECT ( "SELECT COUNT(`car-id`) `nrows` FROM `{p}car-markmodel` WHERE `mark-id` = " . $mark_id . " AND `model-id` IN (" . $model_IDs . ");" );
		if ($_SELECT) {
			$queryArr = array (0 => $_SELECT ["nrows"], 1 => ", `{p}car-markmodel` WHERE ((`mark-id` = " . $mark_id . " AND `model-id` IN (" . $model_IDs . ")) AND `{p}car-markmodel`.`car-id` = `{p}cars`.`car-id`)" );
		}
	} else {
		$queryArr = array (0 => $_SESSION ["nPages"], 1 => ", `{p}car-markmodel` WHERE ((`mark-id` = " . $mark_id . " AND `model-id` IN (" . $model_IDs . ")) AND `{p}car-markmodel`.`car-id` = `{p}cars`.`car-id`)" );
	}
	MakeSearchTable ( $queryArr, $tmpT );
	$tmpT ["search-rez"] = $queryArr [0] . " результата(ов) поиска";
	// формирование страницы
	$_Main->MakePage ( "page.search_rez", $tmpT, "page-search_rez" );
	return 0;
}

// отображение результатов поиска
function pageSearch() {
	global $_Main;
	$tmpT = array ("site-title" => "Результаты поиска: легковые автомобиля на autode.net", "site-links" => "<h>/search-full</h><t>Поиск легкового автомобиля</t>", "title" => "Поиск автомобилей", "search-models" => "", "mark-name" => "", "model-links" => "", "search-rez" => "", "search-rows" => "", "search-pages" => "" );
	// обновление запроса
	if ((date ( "i" ) > 10 && date ( "i" ) < 30) || (date ( "i" ) > 40 && date ( "i" ) <= 59)) {
		if ($_SESSION ["sUpdate"] == 1) {
			if (isset ( $_SESSION ["nPages"] ) && $_SESSION ["nPages"] !== 0) {
				$bCount = TRUE;
			} else {
				$bCount = FALSE;
			}
		} else {
			$bCount = FALSE;
		}
		$_SESSION ["sUpdate"] = 1;
	} else {
		$bCount = FALSE;
		$_SESSION ["sUpdate"] = 0;
	}
	// результат запроса
	$searchRez = Create_Query ( $bCount );
	$_SESSION ["nPages"] = $searchRez [0];
	if ($searchRez [0] > 0) {
		$url = MakeSearchTable ( $searchRez, $tmpT );
	}
	$tmpT ["site-links"] .= "<h></h><t>" . $searchRez [0] . " результата(ов)</t>";
	$tmpT ["search-rez"] .= $searchRez [0] . " результата(ов) поиска";
	$url = ($url != "") ? ("?" . $url) : ("");
	// формирование страницы
	$_Main->MakePage ( "page.search_rez", $tmpT, "page-search_rez" );
	return 0;
}

// формирование таблицы вывода
function MakeSearchTable($queryArr, &$tmpT) {
	global $_MYSQL, $_Lang, $_SEF, $_TPL;
	$href_search = "";
	// количество страниц
	$nPages = ceil ( $queryArr [0] / 20 );
	// текущая страница
	$page = (isset ( $_GET ["page"] )) ? ($_GET ["page"]) : (1);
	$start = ($page - 1) * 20;
	// выбор машин
	$_SELECT = $_MYSQL->SELECT_LIMIT ( "SELECT `{p}cars`.`car-id` FROM `{p}cars`" . $queryArr ["1"] . " ORDER BY `car-date_add` DESC", $start, 20, MYSQL_SALL );
	if (! $_SELECT) {
		return 0;
	}
	$car_IDs = ID_toSQL ( $_SELECT );
	// информация
	$colors = "";
	foreach ( $_Lang->color as $o => $v ) {
		$colors .= ", `" . $o . "`";
	}
	$_SELECT = $_MYSQL->SELECT ( "SELECT `car-name`, `car`.`car-id`, `car-type`, `car-new`, `car-damaged`, `car-safe-label`, `car-power`, `car-gearbox`, `car-climat-contr`, `car-fuel_rcomb`, `car-fuel_rcity`, `car-fuel_rcountry`, `car-co2_comb`, `car-freg`, `car-mileage`, `car-date_add`, `o-check`, `o-new-check`, `o-ever-check`, `o-power-steering`, `o-central-locking`, `o-light_wheels`, `p-brutto`, `p-price`, `p-price-cur`, `p-netto`, `p-netto-cur`" . $colors . ", `i-thumb` FROM `{p}cars` `car` LEFT OUTER JOIN `{p}car-options` `o` ON `o`.`car-id` = `car`.`car-id` LEFT OUTER JOIN `{p}car-price` `p` ON `p`.`car-id` = `car`.`car-id` LEFT OUTER JOIN `{p}car-colors` `c` ON `c`.`car-id` = `car`.`car-id` LEFT OUTER JOIN `{p}car-images` `i` ON `i`.`car-id` = `car`.`car-id` WHERE `car`.`car-id` IN (" . $car_IDs . ") GROUP BY `car`.`car-id` ORDER BY `car-date_add` DESC", MYSQL_SQUERY );
	if (! $_SELECT) {
		return 0;
	}
	// основные элементы
	$_TPL->Load ( "page.search_rez", "power-row" );
	$_TPL->Load ( "page.search_rez", "table_line" );
	// ссылка на страницу поиска
	$tURL = "{site_url}";
	$_SESSION ["nPages"] = $queryArr [0];
	$t = "";
	foreach ( $_GET as $o => $v ) {
		if ($o === "page") {
			continue;
		} elseif ($o === 0 || $o === 1 || $o === 2) {
			$tURL .= "/" . $_SEF->Encode ( $v );
		} elseif (is_array ( $v )) {
			foreach ( $v as $o1 => $v1 ) {
				$href_earch .= $t . $o . "[]=" . $v1;
				$t = "&";
			}
		} else {
			$href_search .= $t . $o . "=" . $v;
			$t = "&";
		}
	}
	// формирвание таблицы
	$_TPL->Load ( "page.search_rez", "car-row" );
	$_TPL->Load ( "page.search_rez", "table_line" );
	while ( $car = $_MYSQL->FETCH_Array ( $_SELECT ) ) {
		$tArr = array ("img-src" => ($car ["i-thumb"] != "") ? ($car ["i-thumb"]) : ("/images/no_car.gif"), "car-href" => "{site_url}/car/" . $car ["car-id"], "car-name" => $car ["car-name"], "car-opis" => "", "car-freg" => ($car ["car-freg"] != "0000-00-00") ? ($car ["car-freg"]) : (""), "car-mileage" => $car ["car-mileage"] . " км", "car-price" => "", "car-date_add" => "" );
		// тип
		if ($car ["car-type"] != 0) {
			$tArr ["car-opis"] = "<strong>" . $_Lang->carText [$car ["car-type"]] . "</strong><br />";
		}
		// новый
		if ($car ["car-new"] == 1) {
			$tArr ["car-opis"] .= "<strong>" . $_Lang->Text ["car-new"] . "</strong><br />";
		}
		// поврежденное 
		if ($car ["car-damaged"] == 1) {
			$tArr ["car-opis"] .= "<strong><span style=\"color: gray;\">" . $_Lang->Text ["car-damaged"] . "</span></strong><br />";
		}
		// новый общий осмотр
		if ($car ["o-ever-check"] != "0000-00-00") {
			$tArr ["car-opis"] .= $_Lang->Text ["o-ever-check"] . "<br />";
		}
		// общий осмотр
		if ($car ["o-check"] != "0000-00-00") {
			$tArr ["car-opis"] .= $_Lang->Text ["o-check"] . " " . $car ["o-check"] . "<br />";
		}
		// мощность
		if ($car ["car-power"] != 0) {
			$tArr ["car-opis"] .= $car ["car-power"] . " кВт (" . round ( $car ["car-power"] * 1.36 ) . " PS), ";
		}
		// цвета
		$opis_t = "";
		foreach ( $_Lang->color as $o => $v ) {
			if ($car [$o] == 1) {
				if ($opis_t != "") {
					$opis_t .= ", ";
				}
				$opis_t .= $v;
			}
		}
		// коробка передач
		if ($car ["car-gearbox"] != 0) {
			if ($opis_t != "") {
				$opis_t .= ", ";
			}
			$opis_t .= $_Lang->gearText [$car ["car-gearbox"]];
		}
		// климат контроль
		if ($car ["car-climat-contr"] != 0) {
			if ($opis_t != "") {
				$opis_t .= ", ";
			}
			$opis_t .= $_Lang->climText [$car ["car-climat-contr"]];
		}
		//Колеса из легкого сплава
		if ($car ["o-light_wheels"] == 1) {
			if ($opis_t != "") {
				$opis_t .= ", ";
			}
			$opis_t .= $_Lang->Text ["o-light_wheels"];
		}
		// Центральный замок
		if ($car ["o-central-locking"] == 1) {
			if ($opis_t != "") {
				$opis_t .= ", ";
			}
			$opis_t .= $_Lang->Text ["o-central-locking"];
		}
		// Рулевой механизм с усилителем
		if ($car ["o-power-steering"] == 1) {
			if ($opis_t != "") {
				$opis_t .= ", ";
			}
			$opis_t .= $_Lang->Text ["o-power-steering"];
		}
		// наклейка
		if ($car ["car-safe-label"] != 0) {
			if ($opis_t != "") {
				$opis_t .= ", ";
			}
			$opis_t .= $_Lang->Text ["car-safe-label"] . " " . $car ["car-safe-label"] . $_Lang->safeLabe [$car ["car-safe-label"]];
		}
		// Расход топлива комбинированный
		if ($car ["car-fuel_rcomb"] != "") {
			if ($opis_t != "") {
				$opis_t .= ", ";
			}
			$opis_t .= $_Lang->Text ["car-fuel_rcomb"] . " " . $car ["car-fuel_rcomb"];
		}
		// Расход топлива (городской)
		if ($car ["car-fuel_rcity"] != "") {
			if ($opis_t != "") {
				$opis_t .= ", ";
			}
			$opis_t .= $_Lang->Text ["car-fuel_rcity"] . " " . $car ["car-fuel_rcity"];
		}
		// Расход топлива (загородный)
		if ($car ["car-fuel_rcountry"] != "") {
			if ($opis_t != "") {
				$opis_t .= ", ";
			}
			$opis_t .= $_Lang->Text ["car-fuel_rcountry"] . " " . $car ["car-fuel_rcountry"];
		}
		// Комбинированный уровень CO2
		if ($car ["car-co2_comb"] != "") {
			if ($opis_t != "") {
				$opis_t .= ", ";
			}
			$opis_t .= $_Lang->Text ["car-co2_comb"] . " " . $car ["car-co2_comb"];
		}
		$tArr ["car-opis"] .= $opis_t;
		// цена
		if ($car ["p-brutto"] == 1) {
			$tArr ["car-price"] .= "<strong>" . $car ["p-price"] . " " . $car ["p-price-cur"] . " (Брутто)</strong><br /><strong>" . $car ["p-netto"] . " " . $car ["p-netto-cur"] . " (Нетто)</strong>";
		} else {
			$tArr ["car-price"] .= "<strong>" . $car ["p-price"] . " " . $car ["p-price-cur"] . "</strong>";
		}
		// дата добавления
		$tArr ["car-date_add"] .= "Добавлено <br />" . $car ["car-date_add"] . "</td></tr>";
		// запись строки
		$tmpT ["search-rows"] .= $_TPL->Show ( "car-row", $tArr, TPL_NOCLEAR );
		$tmpT ["search-rows"] .= $_TPL->Show ( "table_line", NULL, TPL_NOCLEAR );
	}
	// очистка
	$_TPL->Clear ( "car-row" );
	$_TPL->Clear ( "table_line" );
	// навигация по страницам
	$tmpT ["search-pages"] = "<ul>";
	if ($page > 1) {
		$url = $tURL . (($href_search != "") ? ("?" . $href_search) : (""));
		$tmpT ["search-pages"] .= "<li><a href=\"" . $url . "\" class=\"page\"><<</a></li>";
		$url = $tURL . (($href_search != "") ? ("?page=" . ($page - 1) . "&" . $href_search) : ("?page=" . ($page - 1)));
		$tmpT ["search-pages"] .= "<li><a href=\"" . $url . "\" class=\"page\"><-</a></li>";
	}
	$links = "";
	$i = 6;
	if ($page < 4) {
		$tpage = $page + 6 - $page;
	} else {
		$tpage = $page + 2;
	}
	while ( $i > 0 ) {
		$url = $tURL . (($href_search != "") ? ("?page=" . $tpage . "&" . $href_search) : ("?page=" . $tpage));
		if ($tpage < 1) {
			break;
		} elseif ($tpage == $page) {
			$links = "<li><b>" . $page . "</b></li>" . $links;
		} elseif ($tpage == 1) {
			$links = "<li><a href=\"" . $tURL . "\" class=\"page\">" . $tpage . "</a></li>" . $links;
		} elseif ($tpage <= $nPages) {
			$links = "<li><a href=\"" . $url . "\" class=\"page\">" . $tpage . "</a></li>" . $links;
		}
		$i --;
		$tpage --;
	}
	$tmpT ["search-pages"] .= $links . "<li>.. из " . $nPages . "</li>";
	if ($page < $nPages) {
		$url = $tURL . (($href_search != "") ? ("?page=" . ($page + 1) . "&" . $href_search) : ("?page=" . ($page + 1)));
		$tmpT ["search-pages"] .= "<li><a href=\"" . $url . "\" class=\"page\">-></a></li>";
		$url = $tURL . (($href_search != "") ? ("?page=" . $nPages . "&" . $href_search) : ("?page=" . $nPages));
		$tmpT ["search-pages"] .= "<li><a href=\"" . $url . "\" class=\"page\">>></a></li>";
	}
	$tmpT ["search-pages"] .= "</ul>";
	return $href_search;
}
?>